/**
 * Created by luckyjing on 16/2/5.
 * 创建Mongoose UserSchema模式,定义User模型,供其他部件使用
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    crypto = require('crypto');
var UserSchema = new Schema({
    firstName: String,
    lastName: String,
    email: {
        type: String,
        trim: true,
        unique: true
    },
    username: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        validate: [function (password) {
            return password && password.length >= 6;
        }, '密码至少为6位']
    },
    salt: {
        type: String
    },
    created: {
        type: Date,
        default: Date.now
    },
    website: {
        type: String,
        set: function (url) {
            if (!url) {
                return url
            } else {
                if (url.indexOf('http://') !== 0 && url.indexOf('https://') !== 0) {
                    url = 'http://' + url;
                }
                return url;
            }
        }
    },
    sex: {
        type: String,
        enum: ['男', '女']
    },
    provider: {
        type: String,
        required: 'Provider is required'
    },
    providerId: String,
    providerData: {}
});
//虚属性,fullName是 通过 现有字段得到的
UserSchema.virtual('fullName').get(function () {
    return this.firstName + ' ' + this.lastName;
});
// 类方法,去查找文档
UserSchema.statics.findOneByEmail = function (email, callback) {
    this.findOne({email: email}, callback);
};
UserSchema.statics.findUniqueUsername = function (username, suffix, callback) {
    var _this = this;
    var possibleUsername = username + (suffix || '');
    _this.findOne({
        username: possibleUsername
    }, function (err, user) {
        if (!err) {
            if (!user) {
                callback(possibleUsername);
            } else {
                return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
            }
        } else {
            callback(null);
        }
    })
};
//密码验证策略
UserSchema.methods.authenticate = function (password) {
    return this.password === this.hashPassword(password);
};
//密码加密策略
UserSchema.methods.hashPassword = function (password) {
    return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
};
//在存储用户密码之前,需要对密码进行加盐和哈希操作
UserSchema.pre('save', function (next) {
    if (this.password) {
        this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
        this.password = this.hashPassword(this.password);
    }
    next();
});
// 一般输出的时候是res.json(user),为了让在转换前执行,就得调用下面这句话
UserSchema.set('toJSON', {getters: true, virtuals: true});
mongoose.model('User', UserSchema);